<template>
  <div>
    <div class="top-bg" >
      <div class="item">
        <div class="first mr-10">用户姓名:</div>
        <el-input placeholder="请输入用户姓名" clearable maxlength="50" v-model="params.userName"></el-input>
      </div>
      <div class="item">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetClick">重置</el-button>
        <div class="ml-10 flex-center mr-10">
          <el-button @click="importUserClick">导入用户</el-button>
          <div>
            <div class="font13 gray ml-10">导入用户的初始密码是123456</div>
            <div  class="font13 gray ml-10">若用户已存在，则会更新余额</div>
          </div>
        </div>
        <el-button v-if="userInfo.level<3" @click="exportUser">导出用户</el-button>
      </div>
    </div>
    <div class="bg">
      <el-table :data="dataList"  stripe style="width: 100%;" border :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}">
        <el-table-column prop="userName" label="用户姓名" ></el-table-column>
        <el-table-column prop="phone" label="手机号" >
          <template slot-scope="scope">
            <span>{{scope.row.phone||'-'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="用户等级" >
          <template slot-scope="scope">
            <span>{{getUserLevelName(scope.row.level)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="余额">
          <template slot-scope="scope">
            <span>{{scope.row.score||0}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="注册时间"></el-table-column>
        <el-table-column prop="type" label="账户状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type === 1" type="success">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="flagSend" label="操作" v-if="userInfo.level<3">
          <template slot-scope="scope">
            <el-button type="text" :disabled="userInfo.level>=scope.row.level" size="small" @click="changeScoreClick(scope.row)">调整余额</el-button>
            <el-button type="text" v-if="userInfo.level === 1&&scope.row.level>1" :disabled="userInfo.level>=scope.row.level" size="small" @click="changeLevelClick(scope.row)">调整等级</el-button>
            <el-button type="text" :disabled="userInfo.level>=scope.row.level" size="small" @click="changeTypeClick(scope.row)">{{scope.row.type===1?'禁用':'启用'}}</el-button>
            <el-button type="text" :disabled="userInfo.level>=scope.row.level" size="small" @click="deleteClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange"
                     :current-page="params.page" :page-sizes="[10, 20, 30, 50]" :page-size="params.pageSize"
                     :layout="params.total<10?'->,total':'->,total, sizes, prev, pager, next, jumper'" :total="params.total">
      </el-pagination>
    </div>
    <el-dialog title="修改用户等级" width="500px" v-if="changeLevelFlag" :visible.sync="changeLevelFlag" append-to-body :close-on-click-modal="false">
      <div class="font14 mb-20">
        <span class="mr-10">用户名称：</span>
        <span>{{currentChoseUser.userName||'-'}}</span>
      </div>
      <div class="font14 mb-20 flex-start">
        <span class="mr-10">等级调整：</span>
        <div>
          <el-select v-model="currentChoseUser.level" placeholder="请选择用户等级" class="mb-10">
            <el-option v-for="item in levelList" :key="item.level" :label="item.name" :value="item.level"></el-option>
          </el-select>
          <div class="font12 gray">您可以调整用户的等级为管理员或普通用户</div>
        </div>
      </div>
      <div class="flex-center-center">
        <el-button @click="cancelChangeLevel">取消</el-button>
        <el-button type="primary" @click="changeLevelReq">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="调整用户余额" width="500px" v-if="changeScoreFlag" :visible.sync="changeScoreFlag" append-to-body :close-on-click-modal="false">
      <div class="font14 mb-20">
        <span class="mr-10">用户名称：</span>
        <span>{{currentChoseUser.userName||'-'}}</span>
        <span class="red-txt font13 ml-10">{{'当前余额：'+(currentChoseUser.score||'0')}}</span>
      </div>
      <div class="font14 mb-20 flex-center">
        <span class="mr-10">余额调整：</span>
        <div>
          <el-select v-model="scoreAction" placeholder="请选择金额操作类型">
            <el-option v-for="item in actionList" :key="item.value" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </div>
      </div>
      <div class="font14 mb-20">
        <span class="mr-10">调整金额：</span>
        <el-input type="number" oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}" class="mw300" v-model="actionScoreAmount"></el-input>
      </div>
      <div class="flex-center-center">
        <el-button @click="cancelScoreClick">取消</el-button>
        <el-button type="primary" @click="submitScoreClick">确定</el-button>
      </div>
    </el-dialog>
    <input :key="inputKey" type="file" ref="fileExcel" :multiple="false"  style="display: none" accept=".xls,.xlsx" @change="handleChange"></input>
  </div>
</template>

<script>
import {getStore} from "js-utils";
import {
  ORDERING_GET_EXPORT_ALL_USERS,
  ORDERING_GET_USERS_LIST, ORDERING_ORDERING_POST, ORDERING_POST_USERS_CREATE_BATCH,
  ORDERING_POST_USERS_DELETE,
  ORDERING_POST_USERS_LEVEL_CHANGE, ORDERING_POST_USERS_SCORE_CHANGE,
  ORDERING_POST_USERS_TYPE
} from "@/assets/const/api";
import {excelSerialToDateString, readFile} from "@/config/tools";
import * as XLSX from "@/config/xlsx.mini";
import {Validate} from "js-utils/validate";
import {mapState} from "vuex";
import {exportExcel} from "js-utils/excel";

export default {
  name: '',
  mixins: [],
  components: {},
  props: {},
  computed:{
    userInfo(){
      return this.$store.state.userInfo||{};
    }
  },
  data () {
    return {
      dataList:[],
      levelList:[{name:'管理员',level:2},{name:'注册用户',level:3}],
      changeLevelFlag:false,
      changeScoreFlag:false,
      currentChoseUser:{},
      inputKey:0,
      scoreAction:1,//1加2减
      actionScoreAmount:0,
      actionList:[{value:1,name:'充值'},{value:2,name:'扣减'}],
      params:{
        userName:'',
        pageSize:10,
        page:1,
        total:0,
      }
    }
  },
  created() {
    this.resetData()
    this.getData()
  },
  methods:{
    resetData(){
      this.params.userName = ''
    },
    exportUser(){
      this.$http.get(ORDERING_GET_EXPORT_ALL_USERS).then(res=>{
        if(res.code === 200){
          let header = {userName:'用户姓名',score:'金额'}
          exportExcel(res.data, header, '用户余额明细' , "xlsx");
        }
      })
    },
    getData(){
      this.$http.get(ORDERING_GET_USERS_LIST,this.params).then(res=>{
        if(res.code === 200){
          this.dataList = res.data.data
          this.params.total = res.data.total
        }
      })
    },
    getUserLevelName(level){
      if (level === 1){
        return '超级管理员'
      }else if(level ===2){
        return '管理员'
      }else if(level ===3){
        return '注册用户'
      }else if(level ===4){
        return '厨师'
      }
      return ''
    },
    changeScoreClick(row){
      this.currentChoseUser = row
      this.changeScoreFlag = true
    },
    changeLevelClick(row){
      this.currentChoseUser = row
      this.changeLevelFlag = true
    },
    changeLevelReq(){
      this.$http.post(ORDERING_POST_USERS_LEVEL_CHANGE,this.currentChoseUser).then(res=>{
        if(res.code ===200){
          this.$message.success('操作成功')
          this.getData()
        }
        this.changeLevelFlag = false
      })
    },
    changeTypeClick(row){
      let type
      if (row.type === 1){
        type = 2
      }else{
        type = 1
      }
      let dic = {type:type,userId:row.id}
      this.$http.post(ORDERING_POST_USERS_TYPE,dic).then(res=>{
        if(res.code ===200){
          this.$message.success('操作成功')
          this.getData()
        }
      })
    },
    deleteClick(row){
      this.$confirm('确认删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post(ORDERING_POST_USERS_DELETE,{userId:row.id}).then(res=>{
          if (res.code === 200){
            this.$message.success('操作成功')
            this.params.page = 1
            this.getData()
          }
        })
      }).catch(()=>{})
    },
    handleCurrentChange(val){
      this.params.page = val
      this.getData()
    },
    cancelChangeLevel(){
      this.changeLevelFlag = false
      this.currentChoseUser = {}
    },
    cancelScoreClick(){
      this.changeScoreFlag = false
      this.actionScoreAmount = 0
      this.currentChoseUser = {}
    },
    submitScoreClick(){
      if (Number(this.actionScoreAmount) <= 0){
        this.$message.error('金额调整必须大于0')
        return
      }
      this.$http.post(ORDERING_POST_USERS_SCORE_CHANGE,{userId:this.currentChoseUser.id,score:this.actionScoreAmount,type:this.scoreAction,refer:'charge'}).then(res=>{
        if (res.code === 200){
          this.$message.success('操作成功')
          this.params.page = 1
          this.getData()
        }
        this.cancelScoreClick()
      })
    },
    handleSizeChange(val){
      this.params.pageSize = val
      this.getData()
    },
    handleSearch(){
      this.getData()
    },
    resetClick(){
      this.params.page = 1
      this.params.userName = ''
      this.getData()
    },
    importUserClick(){
      this.$refs.fileExcel.click()
    },
    async handleChange(e) {
      if (e.target.files.length === 0) {
        this.$message.error('选择文件不能为空')
        return
      }
      this.fileObj = e
      let fileName = e.target.value.split('\\').pop().replace(/\..+$/, "");
      if (!fileName || fileName.length === 0) {
        fileName = 'userScore'
      }
      let file = e.target.files[0]
      this.fileObj = file
      let data = await readFile(file)
      let workbook = XLSX.read(data, { type: "binary" });

      //拿到第一个sheet表的数据，把第一个表格的数据转换成JSON数据
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      let dataJsons = XLSX.utils.sheet_to_json(worksheet);
      console.log(dataJsons)
      if (!Validate.isEmpty(dataJsons)){
        let finalList = []
        dataJsons.forEach(e=>{
          let dic = {userName:e['用户姓名']||'-',  score:e['金额']||0}
          finalList.push(dic)
        })
        this.submitBatch(finalList)
      }
    },
    submitBatch(finalList){
      this.$http.post(ORDERING_POST_USERS_CREATE_BATCH,{userList:finalList}).then(res=>{
        if(res.code === 200){
          this.$message.success('导入成功')
          this.resetClick()
        }
        this.inputKey ++;
      })
    }
  }
}
</script>

<style scoped lang="scss">
.bg{
  background-color: white;
  padding: 20px;
}
.top-bg{
  background-color: #f9f9f9;
  border: 1px solid #ebeef5;
  min-height: 60px;
  margin-bottom: 15px;
  flex-wrap: wrap;
  padding: 18px 0 0;
  display: flex;
  align-items: center;
  .item{
    display: flex;
    align-items: center;
    margin-right: 10px;
    margin-bottom: 18px;
    flex-shrink: 0;

  }
  .first{
    min-width: 100px;
    text-align: right;
  }
}
</style>